//
//  UIView+Extension.swift
//  TuneMate
//
//  Created by 丸子 on 2023/11/23.
//

import UIKit

public enum ColorLocationStyle:Int {
    case topToBottom = 0
    case leftToRight = 1
}
extension UIView {
    // 设置全部圆角
    @available(iOS 11.0, *)
    func allRound(_ cornerRadius: CGFloat) {
        self.clipsToBounds = true
        self.layer.cornerRadius = cornerRadius
        self.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner, .layerMaxXMinYCorner]
    }
    
    //设置部分圆角
    @available(iOS 11.0, *)
    func corners(_ maskedCorners: CACornerMask, cornerRadius: CGFloat) {
        self.clipsToBounds = true
        self.layer.maskedCorners = maskedCorners
        self.layer.cornerRadius = cornerRadius
    }
    
    var parentViewController: UIViewController? {
         var responder: UIResponder? = self
         while let nextResponder = responder?.next {
             responder = nextResponder
             if let viewController = responder as? UIViewController {
                 return viewController
             }
         }
         return nil
     }
    
    /// 部分圆角
    ///
    /// - Parameters:
    ///   - corners: 需要实现为圆角的角，可传入多个
    ///   - radii: 圆角半径
    public func corner(byRoundingCorners corners: UIRectCorner, radii: CGFloat) {
        self.layoutIfNeeded()
        superview?.layoutIfNeeded()
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }

    /// View添加渐变
    /// - Parameters:
    ///   - startPoint: 起始点
    ///   - endPoint: 结束点
    ///   - colors: 颜色集
    public func gradientColor(_ startPoint: CGPoint, _ endPoint: CGPoint, _ colors: [UIColor]) {
        guard startPoint.x >= 0, startPoint.x <= 1, startPoint.y >= 0, startPoint.y <= 1, endPoint.x >= 0, endPoint.x <= 1, endPoint.y >= 0, endPoint.y <= 1 else { return }
        removeGradientLayer()
        layoutIfNeeded()
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        gradientLayer.colors = colors.map { $0.cgColor }
        gradientLayer.cornerRadius = layer.cornerRadius
        gradientLayer.masksToBounds = true
        gradientLayer.locations = [0, 1]
        layer.insertSublayer(gradientLayer, at: 0)
    }

    public func themeGradient(_ colors:[UIColor]?, _ style:ColorLocationStyle) {
        var colors = colors
        if colors == nil {
            colors = [UIColor(hexString: "#31EBFD"), UIColor(hexString: "#29FF8A")]
            
        }
        guard let colors = colors else { return }
        if style == .leftToRight {
            gradientColor(CGPoint(x: 0, y: 0.5), CGPoint(x: 1, y: 0.5), colors)
        }else if style == .topToBottom{
            gradientColor(CGPoint(x: 0.5, y: 0), CGPoint(x: 0.5, y: 1), colors)
        }
       
    }
    
    /// 移除渐变
    public func removeGradientLayer() {
        if let sl = self.layer.sublayers {
            for layer in sl {
                if layer.isKind(of: CAGradientLayer.self) {
                    layer.removeFromSuperlayer()
                }
            }
        }
    }
    
    public var x:CGFloat {
        get {
            return self.frame.origin.x
        }
        set(newLeft) {
            var frame = self.frame
            frame.origin.x = newLeft
            self.frame = frame
        }
    }
    
    public var y:CGFloat {
        get {
            return self.frame.origin.y
        }
        
        set(newTop) {
            var frame = self.frame
            frame.origin.y = newTop
            self.frame = frame
        }
    }
    
    public var width:CGFloat {
        get {
            return self.frame.size.width
        }
        
        set(newWidth) {
            var frame = self.frame
            frame.size.width = newWidth
            self.frame = frame
        }
    }
    
    public var height:CGFloat {
        get {
            return self.frame.size.height
        }
        
        set(newHeight) {
            var frame = self.frame
            frame.size.height = newHeight
            self.frame = frame
        }
    }
    
    public var right:CGFloat {
        get {
            return self.x + self.width
        }
    }
    
    public var bottom:CGFloat {
        get {
            return self.y + self.height
        }
    }
    
    public var centerX:CGFloat {
        get {
            return self.center.x
        }
        
        set(newCenterX) {
            var center = self.center
            center.x = newCenterX
            self.center = center
        }
    }
    
    public var centerY:CGFloat {
        get {
            return self.center.y
        }
        
        set(newCenterY) {
            var center = self.center
            center.y = newCenterY
            self.center = center
        }
    }
    
    func sun(_ supview: UIView) -> SnapKit.ConstraintViewDSL {
        supview.addSubview(self)
        return self.snp
    }
  
}
/// 定义一个协议
protocol NibLoadable {
    /// 具体实现写到 extension 中
}

/// 加载xib
extension NibLoadable where Self : UIView {
    /* Xib 和 类名 同名
     * lazy var headerView = HomeHeaderView.loadFromNib()
     *
     * Xib 中多个 View 视图
     * lazy var sectionView = Level1SectionView.loadFromNib("Level1HeaderView",index: 1) */
    
    
    /// 协议中不能定义class
    static func loadFromNib(_ nibname:String? = nil,index:Int = 0) -> Self { // Self(大写)当前类对象
        /// self(小写)当前对象
        let loadName = nibname == nil ? "\(Self.self)" : nibname!
        return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)![index] as! Self
    }
}
extension UIViewController {
    var safeTop: SnapKit.ConstraintItem {

        if #available(iOS 11.0, *) {
            return view.safeAreaLayoutGuide.snp.top
        } else {
            return topLayoutGuide.snp.bottom
        }
    }

    var safeBottom: SnapKit.ConstraintItem {
        if #available(iOS 11.0, *) {
            return view.safeAreaLayoutGuide.snp.bottom
        } else {
            return bottomLayoutGuide.snp.top
        }
    }
    
    func popSelf(animation: Bool, completionHandler: (() -> Void)? = nil) {
        DispatchQueue.main.async {
            if let presentingViewController = self.presentingViewController {
                self.dismiss(animated: animation, completion: completionHandler)
            } else if self.navigationController?.topViewController == self {
                self.navigationController?.popViewController(animated: animation)
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: completionHandler ?? {})
            } else {
                debugPrint("UIViewController")
            }
        }
    }
  
    func renderActivitySheet(title: String?, actionTitles: [String], cancelTitle: String, handler: ((UIAlertAction, Int) -> Void)?) {
        // 创建一个空的SheetAction数组
        var actions: [SheetAction] = []
        // 遍历actionTitles数组
        for title in actionTitles {
            // 使用每个标题创建一个SheetAction对象，并添加到actions数组中
            actions.append(SheetAction(title: title))
        }
        // 调用另一个版本的renderActivitySheet函数
        renderActivitySheet(title: title, actions: actions, cancelTitle: cancelTitle, handler: handler)
    }
    
    func renderActivitySheet(title: String?, actions: [SheetAction], cancelTitle: String?, handler: ((UIAlertAction, Int) -> Void)?) {
        // 结束当前窗口的编辑状态
        self.view.window?.endEditing(true)
        // 创建一个UIAlertController对象
        let alertController = RPAlertViewController(title: nil, message: title, preferredStyle: .actionSheet)

        // 遍历actions数组
        for action in actions {
            // 创建一个UIAlertAction对象
            let alertAction = UIAlertAction(title: action.title, style: action.destructive ? .destructive : .default) { alertAction in
                // 如果handler存在，则调用handler
                if let handler = handler {
                    handler(alertAction, actions.firstIndex(where: { $0.title == action.title }) ?? -1)
                }
            }
            // 将alertAction添加到alertController中
            alertController.addAction(alertAction)
        }

        // 如果cancelTitle存在
        if let cancelTitle = cancelTitle {
            // 创建一个取消按钮
            let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { alertAction in
                // 如果handler存在，则调用handler
                if let handler = handler {
                    handler(alertAction, -1)
                }
            }
            // 将取消按钮添加到alertController中
            alertController.addAction(cancelAction)
        }
 
        // 如果是 iPad
          if UIDevice.current.userInterfaceIdiom == .pad {
              if let popoverController = alertController.popoverPresentationController {
                  popoverController.sourceView = self.view // 设置弹出的源视图
                  popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // 设置弹出的源视图的区域
              }
          }

          // 显示alertController
          self.present(alertController, animated: true, completion: nil)
    }
    
    func pushViewControllerhidesBottom_k(_ viewController: UIViewController, animated: Bool = true) {
        viewController.hidesBottomBarWhenPushed = true
        if let navigationController = self as? UINavigationController {
            navigationController.pushViewController(viewController, animated: animated)
        } else {
            navigationController?.pushViewController(viewController, animated: animated)
        }
    }
    /// 判断是否包含某个页面

    
    func popViewController_k(animated: Bool = true)  {
        if let navigationController = self as? UINavigationController {
            navigationController.popViewController(animated: animated)
        } else {
            navigationController?.popViewController(animated: animated)
        }
    }
}
class SheetAction {
    var title: String
    var destructive: Bool
    init(title: String) {
        self.title = title
        self.destructive = false
    }
    init(title: String, destructive: Bool) {
        self.title = title
        self.destructive = destructive
    }
}
// RPAlertViewController 类继承自 UIAlertController
class RPAlertViewController: UIAlertController {
    // viewDidLoad 方法
    override func viewDidLoad() {
        super.viewDidLoad()
        // 视图加载完成后执行的操作
    }
    
    // 设置颜色的方法
    func setMerryDownplayColor(view: UIView, count: Int) {
        var _count = count
        for subView in view.subviews {
            if subView.frame.height < 1 && subView.frame.height > 0 {
                // 如果子视图的高度小于1且大于0，则设置其背景色
                subView.backgroundColor = UIColor(hexString: "0x2C2C2E")
            } else if subView.frame.width < 1 && subView.frame.width > 0 {
                // 如果子视图的宽度小于1且大于0，则设置其背景色
                subView.backgroundColor = UIColor(hexString: "0x2C2C2E")
            } else {
                if subView.backgroundColor != nil &&
                    !(subView is UILabel) &&
                    !self.view.subviews.contains(subView) {
                    _count += 1
                    if _count > 2 && _count < 5 {
                        // 如果满足特定条件，则设置子视图的背景色
                        subView.backgroundColor = UIColor(hexString: "0x252525")
                    }
                }
                if let firstSubview = subView.subviews.first,
                   let secondSubview = subView.subviews[1] as? UIVisualEffectView {
                    // 如果子视图的子视图满足特定条件，则设置其背景色
                    firstSubview.backgroundColor = UIColor(hexString: "0x252525")
                    if secondSubview.subviews.count > 1 {
                        secondSubview.subviews[1].backgroundColor = UIColor(hexString: "0x252525")
                    }
                }
            }
            if !subView.subviews.isEmpty {
                // 如果子视图还有子视图，则递归调用此方法
                setMerryDownplayColor(view: subView, count: _count)
            }
        }
    }
    
    // 将要移动到父视图控制器的方法
    override func willMove(toParent parent: UIViewController?) {
        // 视图控制器将要移动到父视图控制器时执行的操作
    }
    
    
    
}
extension UIView {
//    
//    
//    /**< 起点 x */
//    var x: CGFloat {
//        get {
//            return frame.origin.x
//        }
//        
//        set {
//            frame = CGRect(x: newValue, y: y, width: width, height: height)
//        }
//    }
//    
//    /**< 起点 y */
//    var y: CGFloat {
//        get {
//            return frame.origin.y
//        }
//        
//        set {
//            frame = CGRect(x: x, y: newValue, width: width, height: height)
//        }
//    }
//    
//    /**< 宽 */
//    var width: CGFloat {
//        get {
//            return frame.size.width
//        }
//        
//        set {
//            frame = CGRect(x: x, y: y, width: newValue, height: height)
//        }
//    }
//
//    /**< 高 */
//    var height: CGFloat {
//        get {
//            return frame.size.height
//        }
//        
//        set {
//            frame = CGRect(x: x, y: y, width: width, height: newValue)
//        }
//    }
//
//    /**< 起点 left */
    var left: CGFloat {
        get {
            return frame.origin.x
        }

        set {
            frame = CGRect(x: newValue, y: y, width: width, height: height)
        }
    }
//    
//    /**< 起点 top */
    var top: CGFloat {
        get {
            return frame.origin.y
        }
        
        set {
            frame = CGRect(x: x, y: newValue, width: width, height: height)
        }
    }
//    
//    /**< 右 */
//    var right: CGFloat {
//        get {
//            return x + width
//        }
//        
//        set {
//            x = newValue - width
//        }
//    }
//    
//    /**< 下 */
//    var bottom: CGFloat {
//        get {
//            return y + height
//        }
//        
//        set {
//            y = newValue - height
//        }
//    }
//    
//    /**< 中心 x */
//    var centerX: CGFloat {
//        get {
//            return center.x
//        }
//        
//        set {
//            center = CGPoint(x: newValue, y: center.y)
//        }
//    }
//
//    /**< 中心 y */
//    var centerY: CGFloat {
//        get {
//            return center.y
//        }
//        
//        set {
//            center = CGPoint(x: center.x, y: newValue)
//        }
//    }
//
//    /**< origin */
//    var origin: CGPoint {
//        get {
//            return frame.origin
//        }
//        
//        set {
//            frame = CGRect(x: newValue.x, y: newValue.y, width: width, height: height)
//        }
//    }
//    
//    /**< size */
//    var size: CGSize {
//        get {
//            return frame.size
//        }
//        
//        set {
//            frame = CGRect(x: x, y: y, width: newValue.width, height: newValue.height)
//        }
//    }
//    
//    
//    /**< 右 */
//    var layoutRight: CGFloat {
//        get {
//            return right
//        }
//        
//        set {
//            var suprWidth = UIScreen.main.bounds.size.width
//            if (superview != nil) {
//                suprWidth = superview!.frame.size.width
//            }
//            
//            if (width == 0) {
//                width = suprWidth - left - newValue
//            } else {
//                right = suprWidth - newValue
//            }
//
//        }
//    }
//    
//    /**< 下 */
//    var layoutBottom: CGFloat {
//        get {
//            return bottom
//        }
//        
//        set {
//            var suprHeight = UIScreen.main.bounds.size.height
//            if (self.superview != nil) {
//                suprHeight = self.superview!.frame.size.height
//            }
//            
//            if (height == 0) {
//                height = suprHeight - top - newValue
//            } else {
//                bottom = suprHeight - newValue
//            }
//            
//        }
//    }
}



extension UINavigationController {
    /// 删除某个子控制器
    func removeSubViewController_k(vcName: String) {
        var subControllers: [UIViewController] = []
        let currentVC = viewControllers
        if currentVC.count <= 1 { return }

        for subVC in currentVC {
            let aClass = type(of: subVC).description().components(separatedBy: ".").last
            if aClass != vcName || subVC == visibleViewController {
                subControllers.append(subVC)
            }
        }
        setViewControllers(subControllers, animated: false)
    }
    
    func haveChildViewController_k(vcName: String) -> Bool {
        let currentVC = viewControllers
        for subVC in currentVC {
            let aClass = type(of: subVC).description().components(separatedBy: ".").last
            if aClass == vcName {
                return true
            }
        }
        return false
    }
}
